//
//  AppDelegate.swift
//  TWeibo
//
//  Created by wtw on 15/7/28.
//  Copyright © 2015年 wtw. All rights reserved.
//

import UIKit

/// 定义通知
let TWRootViewControllerSwitchNotification = "TWRootViewControllerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: TWRootViewControllerSwitchNotification, object: nil)
        
        print(UserAcount.sharedUserAccount)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        //设置外观
        setupAppearance()
        
        return true
    }
    
    /// 程序销毁才会执行
    deinit {
        //销毁通知，习惯而已，并不是必须要销毁
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    ///切换控制器  一定要在 AppDelegate中统一修改
    func switchViewController(n: NSNotification) {
        print("切换控制器\(n)")
        let maiVC = n.object as! Bool
        
        window?.rootViewController = maiVC ? MainViewController() : WelcomViewController()
    }
    
    /// 要显示的默认控制器
    private func defaultViewController()->UIViewController {
        //判断用户是否登录，如果没有登录返回主控制器
        if !UserAcount.userLogon {
            return MainViewController()
        }
        //判断是否是新版本，如果是返回新特性，否则进入欢迎界面
        return isNewUpdate() ? NewFeatureCollectionViewController() : WelcomViewController()
    }
    
    /// 检测新版本
    private func isNewUpdate()->Bool {
        //1.检测当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        //2.检测沙盒版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        //3,将当前版本保存至沙盒
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        // iOS 7.0 之后，就不需要同步了，iOS 6.0 之前，如果不同步不会第一时间写入沙盒
         NSUserDefaults.standardUserDefaults().synchronize()
        return currentVersion > sandboxVersion

    }
    
    /// 修改全局外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }

}

